package com.ssc.nav.utils

import com.ssc.nav.data.NavItem
import com.ssc.nav.extension.NavPluginExtension
import org.w3c.dom.Element
import java.io.File
import javax.xml.parsers.DocumentBuilderFactory

/**
 * user: jyt
 * DATA: 2024/9/10
 * TIME: 14:33
 */
object XmlPullParserUtils {

    /**
     * resources标签
     */
    val TAG_RESOURCES ="resources"
    /**
     * item标签
     */
    val TAG_ITEM ="item"



    val ATTRIBUTE_NAME ="name"
    val ATTRIBUTE_CLAZZ ="clazz"
    val ATTRIBUTE_STARTDESTINATION ="startDestination"
    val ATTRIBUTE_TYPE ="type"
    val ATTRIBUTE_NAVIGONE ="navIgone"


    fun xmlRead(config: NavPluginExtension, readFile: File): MutableMap<String, NavItem>{
        val factory = DocumentBuilderFactory.newInstance()
        val builder = factory.newDocumentBuilder()

        // 解析XML文件并返回Document对象
        val document = builder.parse(readFile)

        val nodeList = document.getElementsByTagName(TAG_RESOURCES)
        LogUtils.d(config.isDebugLog,"resources节点数量：${nodeList.length}")
        val map = mutableMapOf<String, NavItem>()
        if (nodeList.length > 0) {
            val resourcesNode = nodeList.item(0) as Element
            val itemNodeList = resourcesNode.getElementsByTagName(TAG_ITEM)
            LogUtils.d(config.isDebugLog,"item节点数量：${itemNodeList.length}")
            for (i in 0 until itemNodeList.length) {

                val itemNode = itemNodeList.item(i) as Element
                val name = itemNode.getAttribute(ATTRIBUTE_NAME)
                val clazz = itemNode.getAttribute(ATTRIBUTE_CLAZZ)
                val startDestination = itemNode.getAttribute(ATTRIBUTE_STARTDESTINATION)
                val type = itemNode.getAttribute(ATTRIBUTE_TYPE)
                val navIgone = itemNode.getAttribute(ATTRIBUTE_NAVIGONE)

                val item = NavItem(name, clazz, startDestination, type, navIgone)
                map.put(name, item)

                LogUtils.d(config.isDebugLog,"节点值:${name}==${type}")
            }
        }
        return map
    }
}